package com.jspica.app.messagespam;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.telephony.SmsMessage;
import android.util.*;

public class BlockedListDAO extends DbManager {

	private static final String tableName = "spam";

	public static final String[] allFields = new String[] {"_id", "sms_body", "sender", "time"};

	public BlockedListDAO(Context mCtx) {
		super(mCtx);
	}

	public Cursor getListAll() throws SQLException {
		Cursor mCursor = mDb.query(tableName, allFields, null, null, null, null, "time desc");
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}

	public Cursor getRowById(long rowID) throws SQLException {
		String where = "_id=" + rowID;
		Cursor mCursor = mDb.query(tableName, allFields, where, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}

	public void insert(SmsMessage sms) {
		ContentValues initialValues = new ContentValues();
		SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		initialValues.put("time", simpleDate.format(new Date()));
		//initialValues.put("sender", sms.getOriginatingAddress());
		initialValues.put("sender", sms.getDisplayOriginatingAddress());
		initialValues.put("sms_body", sms.getMessageBody());
		mDb.insert(tableName, null, initialValues);
	}

	public int deleteAll() {
		return mDb.delete(tableName, null, null);
	}

	public int deleteRow(int id) {
		return mDb.delete(tableName, "_id='" + id + "'", null);
	}
	
	/* white list */
	public Cursor getWhitelist() throws SQLException {
		Cursor mCursor = mDb.rawQuery("SELECT _id, keyword FROM white ORDER BY _id DESC", null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}
	
	public void insertWhitelist(String keyword) {
		mDb.execSQL("INSERT INTO white (keyword) VALUES (\"" + keyword + "\")");
	}
	
	public void deleteWhitelist(int id) {
		mDb.execSQL("DELETE FROM white WHERE _id = " + id);
	}
	
	/* black list */
	public Cursor getBlacklist() throws SQLException {
		Cursor mCursor = mDb.rawQuery("SELECT _id, keyword FROM black ORDER BY _id DESC", null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}
	
	public void insertBlacklist(String keyword) {
		mDb.execSQL("INSERT INTO black (keyword) VALUES (\"" + keyword + "\")");
	}
	
	public void deleteBlacklist(int id) {
		mDb.execSQL("DELETE FROM black WHERE _id = " + id);
	}
}
